<template>
  <view class="statistics-container">
    <view class="tab-box">
      <u-tabs
          :list="tabsList"
          @change="tabsClick"
          :current="current"
          lineColor="#0994f8"
          active-color="#0994f8"
          inactive-color="#666"
          bgColor="transparent"
      ></u-tabs>
    </view>
    
    <!-- 用户统计卡片 -->
    <view class="stat-card">
      <view class="card-title">我的统计</view>
      <view class="stat-grid">
        <view class="stat-item">
          <view class="stat-value">{{ formatQuantity(userStats.totalDevices) }}</view>
          <view class="stat-label">发布总数量</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ formatMoney(userStats.totalValue) }}</view>
          <view class="stat-label">发布总原值</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ formatRate(userStats.totalDevices , userStats.totalValue) }}</view>
          <view class="stat-label">总原值/发布数量</view>
        </view>
      </view>
      <view class="divider"></view>
      <view class="stat-grid">
        <view class="stat-item">
          <view class="stat-value">{{ formatQuantity(userStats.transferOutCount) }}</view>
          <view class="stat-label">调出数量</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ formatMoney(userStats.transferOutValue) }}</view>
          <view class="stat-label">调出总原值</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ formatRate(userStats.transferOutCount , userStats.transferOutValue) }}</view>
          <view class="stat-label">总原值/调出数量</view>
        </view>
      </view>
      <view class="divider"></view>
      <view class="stat-grid">
        <view class="stat-item">
          <view class="stat-value">{{ formatQuantity(userStats.transferInCount) }}</view>
          <view class="stat-label">调入数量</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ formatMoney(userStats.transferInValue) }}</view>
          <view class="stat-label">调入总原值</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ formatRate(userStats.transferInCount, userStats.transferInValue) }}</view>
          <view class="stat-label">总原值/调入数量</view>
        </view>
      </view>
    </view>
    
    <!-- 汇总统计卡片（仅管理员可见） -->
    <view class="stat-card" v-if="isAdmin">
      <view class="card-title">汇总统计</view>
      <view class="stat-grid">
        <view class="stat-item">
          <view class="stat-value">{{ formatQuantity(systemStats.totalDevices) }}</view>
          <view class="stat-label">汇总总数量</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ formatMoney(systemStats.totalValue) }}</view>
          <view class="stat-label">汇总总原值</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ formatRate(systemStats.totalDevices, systemStats.totalValue) }}</view>
          <view class="stat-label">总原值/汇总数量</view>
        </view>
      </view>
    </view>
    
    <!-- 时间段统计卡片 -->
    <view class="stat-card">
      <view class="card-title">时间段统计</view>
      
      <!-- 日期选择器 -->
      <view class="date-picker-container">
        <view class="date-range">
          <view class="date-item" @click="openStartDatePicker">
            <text>{{ dateRange.startDate }}</text>
            <u-icon style="margin-left: 12rpx" name="calendar" size="32" color="#0962c4"></u-icon>
          </view>
          <text class="date-separator">至</text>
          <view class="date-item" @click="openEndDatePicker">
            <text>{{ dateRange.endDate }}</text>
            <u-icon style="margin-left: 12rpx" name="calendar" size="32" color="#0962c4"></u-icon>
          </view>
          <u-icon @click="onSearch" style="margin-left: 12rpx" name="search" size="40" color="#0962c4"></u-icon>
        </view>
      </view>
      
      <!-- 时间段内的调拨统计 -->
      <view class="stat-grid">
        <view class="stat-item">
          <view class="stat-value">{{ formatQuantity(periodStats.transferOutCount) }}</view>
          <view class="stat-label">调出数量</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ formatMoney(periodStats.transferOutValue) }}</view>
          <view class="stat-label">调出总原值</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ formatRate(periodStats.transferOutCount, periodStats.transferOutValue) }}</view>
          <view class="stat-label">调出数量/总原值</view>
        </view>
      </view>
    </view>
    <!-- 日期选择器 -->
    <u-calendar
        v-model="showStartDatePicker"
        @change="confirmStartDate"
        @close="showStartDatePicker = false"
        mode="date"
        :min-date="minDate"
        :max-date="maxDate"
    ></u-calendar>

    <u-calendar
        v-model="showEndDatePicker"
        @change="confirmEndDate"
        @close="showEndDatePicker = false"
        mode="date"
        :max-date="maxDate"
        :min-date="dateRange.startDate || minDate"
    ></u-calendar>
    
    <!-- 加载中提示 -->
    <u-loading-page :loading="loading"></u-loading-page>
  </view>
</template>
<script>
import { mapGetters } from 'vuex'
import dayjs from 'dayjs';

export default {
  name: "static",
  computed: {
    ...mapGetters(['userInfo']),
  },
  data() {
    return {
      tabsList: [
        { name: '全部', value: '' },
        { name: '物资', value: '物资' },
        { name: '设备', value: '设备' },
      ],
      current: 0,
      // 用户统计数据
      userStats: {
        totalDevices: 0,
        totalValue: 0,
        transferOutCount: 0,
        transferOutValue: 0,
        transferInCount: 0,
        transferInValue: 0
      },
      // 汇总统计数据（仅超级管理员可见）
      systemStats: {
        totalDevices: 0,
        totalValue: 0
      },
      // 时间段统计
      dateRange: {
        // 一个月前
        startDate: dayjs().subtract(1, 'month').format('YYYY-MM-DD'),
        endDate: dayjs().format('YYYY-MM-DD')
      },
      periodStats: {
        transferOutCount: 0,
        transferOutValue: 0
      },
      // 日期选择器相关
      showStartDatePicker: false,
      showEndDatePicker: false,
      minDate: dayjs().format('YYYY-MM-DD'),
      maxDate: '2099-01-01',
      // 加载状态
      loading: false,
      isAdmin: false
    }
  },
  onLoad() {
    // 检查用户是否为超级管理员
    this.isAdmin = this.userInfo.level === 2

    this.loadData()
  },
  methods: {
    tabsClick(index) {
      this.current = index;
      this.loadData()
    },
    // 加载所有统计数据
    loadData() {
      this.loading = true

      // 获取用户统计
      this.getUserStats()

      // 如果是管理员，获取汇总统计
      this.getSystemStats()

      // 获取时间段内的调拨统计
      this.getPeriodStats()
    },

    // 获取用户统计
    getUserStats() {
      this.$api.getUserDeviceStats({
        user_id: this.userInfo.id,
        type: this.tabsList[this.current].value
      }).then(res => {
        if (res) {
          this.userStats = res
        }
      }).catch(err => {
        uni.showToast({
          icon: 'none',
          title: '获取用户统计数据失败'
        })
      }).finally(() => {
        this.loading = false
      })
    },

    // 获取汇总统计（仅管理员）
    getSystemStats() {
      if (!this.isAdmin) return
      this.$api.getSystemDeviceStats({
        type: this.tabsList[this.current].value
      }).then(res => {
        if (res) {
          this.systemStats = res
        }
      }).catch(err => {
        uni.showToast({
          icon: 'none',
          title: '获取汇总统计数据失败'
        })
      })
    },

    // 获取时间段内的调拨统计
    getPeriodStats() {
      uni.showLoading()
      this.$api.getTransferStats({
        startDate: this.dateRange.startDate,
        endDate: this.dateRange.endDate,
        type: this.tabsList[this.current].value
      }).then(res => {
        if (res) {
          this.periodStats = res
        }
      }).catch(err => {
        uni.showToast({
          icon: 'none',
          title: '获取时间段统计数据失败'
        })
      })
    },

    // 打开开始日期选择器
    openStartDatePicker() {
      this.showStartDatePicker = true
    },

    // 打开结束日期选择器
    openEndDatePicker() {
      this.showEndDatePicker = true
    },
    onSearch() {
      this.getPeriodStats()
    },
    // 确认开始日期
    confirmStartDate(e) {
      console.log(e)
      this.dateRange.startDate = e.result;
      this.dateRange.endDate = ''
      this.showDatePicker = false;
    },

    // 确认结束日期
    confirmEndDate(e) {
      this.dateRange.endDate = e.result;
      this.showEndDatePicker = false;
    },
    // 格式化金额显示
    formatMoney(value) {
      if (!value && value !== 0) return '0元';
      
      // 将值转换为数字类型
      const num = parseFloat(value);
      
      // 处理亿级别的数字
      if (num >= 100000000) {
        return (num / 100000000).toFixed(2) + '亿元';
      }
      
      // 处理万级别的数字
      if (num >= 10000) {
        return (num / 10000).toFixed(2) + '万元';
      }
      
      // 处理千级别的数字，保留两位小数
      return num.toFixed(2) + '元';
    },
    // 格式化数量显示
    formatQuantity(value) {
      if (!value && value !== 0) return '0';
      
      // 将值转换为数字类型
      const num = parseFloat(value);
      
      // 处理亿级别的数字
      if (num >= 100000000) {
        return (num / 100000000).toFixed(2) + '亿';
      }
      
      // 处理万级别的数字
      if (num >= 10000) {
        return (num / 10000).toFixed(2) + '万';
      }
      
      // 数量通常不需要小数点
      return Math.round(num);
    },
    formatRate(value, total) {
      if (!value || value === 0) return '0';
      if (!total && total !== 0) return '0';
      
      // 计算平均值：总原值/数量
      const rate = total / value;
      
      // 使用formatMoney格式化结果
      return this.formatMoney(rate);
    }
  }
}
</script>

<style scoped lang="scss">
.statistics-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  margin-bottom: 30rpx;
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.stat-card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .card-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
  }
  
  .stat-grid {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;
    
    .stat-item {
      flex: 1;
      text-align: center;
      
      .stat-value {
        font-size: 36rpx;
        font-weight: bold;
        color: #0962c4;
        margin-bottom: 10rpx;
      }
      
      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
  
  .divider {
    height: 1rpx;
    background-color: #eee;
    margin: 10rpx 0;
  }
}

.date-picker-container {
  margin-bottom: 30rpx;
  
  .date-range {
    display: flex;
    align-items: center;
    justify-content: center;
    
    .date-item {
      display: flex;
      align-items: center;
      background-color: #f5f7fa;
      padding: 15rpx 20rpx;
      border-radius: 8rpx;
      font-size: 26rpx;
      color: #333;
      
      u-icon {
        margin-left: 10rpx;
      }
    }
    
    .date-separator {
      margin: 0 20rpx;
      color: #666;
    }
  }
}
</style>